package vn.co.thn.web.demo_app_engine.model;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;

import vn.co.thn.web.demo_app_engine.PMF;

public abstract class CommonModel<T> {
	private BlobstoreService blobstoreService;
	protected  CommonModel() {
	}

	protected CommonModel(BlobstoreService blobstoreService) {
		this.blobstoreService = blobstoreService;
	}

	public BlobstoreService getBlobstoreService() {
		return blobstoreService;
	}

	public void setBlobstoreService(BlobstoreService blobstoreService) {
		this.blobstoreService = blobstoreService;
	}

	protected void deleteb_lobKey(String blobKey) {
		if (blobKey != null) {
			BlobKey blobKeys = new BlobKey(blobKey);
			blobstoreService.delete(blobKeys);
		}
	}

	@SuppressWarnings("unchecked")
	public synchronized List<T> getAll(Class<T> clazz) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		List<T> list = new ArrayList<T>();

		try {
			tx.begin();
			Query q = pm.newQuery(clazz);
			list = (List<T>) q.execute();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		return list;
	}
	@SuppressWarnings("unchecked")
	public synchronized List<T> getAll(Class<T> clazz,String Sort_Orders) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		List<T> list = new ArrayList<T>();

		try {
			tx.begin();
			Query q = pm.newQuery(clazz);
			list = (List<T>) q.execute();
			q.setOrdering(Sort_Orders);
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		return list;
	}
	public synchronized void Add(T obj){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(obj);
		} finally {
			pm.close();
		}
	}

	protected synchronized void Update(T obj) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(obj);
		} finally {
			pm.close();
		}
	}

	protected synchronized  T Delete(Class<T> clazz,Object key){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		T obj=pm.getObjectById(clazz, key);
		try {
			pm.deletePersistent(obj);
		} finally {
			pm.close();
		}
		return obj;
		
	}
	public abstract  void Delete(Object key);
}
